package Day18_网络编程.ZuoYe.Test2;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.net.Socket;
import java.util.Scanner;

/**
 * @author zhangyan
 * @date 2020/5/10 16:56
 */
public class Client {
    public static void main(String[] args) throws Exception {
        //**客户端2**

        //创建客户端Socket对象并指定服务器地址和端口号
        Socket socket = new Socket("localhost", 8888);

        //创建字符缓冲输出流,关流连接通道
        BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(socket.getOutputStream()));

        //创建字符缓冲输入流,关流连接通道
        BufferedReader br = new BufferedReader(new InputStreamReader(socket.getInputStream()));

        //创建Scanner对象
        Scanner sc = new Scanner(System.in);

        //死循环
        while (true) {
            //用户输入
            System.out.println("请输入发给服务端的消息:");
            String massage = sc.nextLine();

            //判断输入的是否为exit
            if (massage.equals("exit")) {
                break;
            }
            //写出数据
            bw.write(massage);
            //换行
           // bw.newLine(); 相当于 socket.shutdownOutput();
            //刷新
            bw.flush();
            socket.shutdownOutput();

            //读取数据
            System.out.println("服务端回复:" + br.readLine());

        }
        //关闭对象
        br.close();
        br.close();
        socket.close();
    }
}
